package com.xixi.canal.client.starter.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * spring util配置类
 *
 * @author rewerma @ 2018-10-20
 * @version 1.0.0
 */
@Component
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext context;

    /*
     * 注入ApplicationContext
     */
    public void setApplicationContext(final ApplicationContext context) throws BeansException {
        // 在加载Spring时自动获得context
        SpringContext.context = context;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static Object getBean(final String beanName) {
        return SpringContext.context.getBean(beanName);
    }

    public static Object getBean(final Class<?> clz) {
        return context.getBean(clz);
    }


    public static Properties getEnvProperties() {
        Environment env = (Environment) SpringContext.getBean(Environment.class);
        Properties properties = null;
        if (env instanceof StandardEnvironment) {
            properties = new Properties();
            for (PropertySource<?> propertySource : ((StandardEnvironment) env).getPropertySources()) {
                if (propertySource instanceof EnumerablePropertySource) {
                    String[] names = ((EnumerablePropertySource<?>) propertySource).getPropertyNames();
                    for (String name : names) {
                        Object val = propertySource.getProperty(name);
                        if (val != null) {
                            properties.put(name, val);
                        }
                    }
                }
            }
        }
        return properties;
    }




}
